package com.bestcem.xm.user.service.impl.third;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.ValidationErrorCodeEnum;
import com.bestcem.xm.user.config.properties.SettingProperties;
import com.bestcem.xm.user.service.third.LuosimaoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * Luosimao服务
 * 文档地址: https://luosimao.com/docs/api/56
 *
 * @author wangyunyun <yunyun.wang@idiaoyan.com>
 * @version v1.0
 * @date 2022/3/7 15:00
 */
@Slf4j
@Service
public class LuosimaoServiceImpl implements LuosimaoService {

    @Autowired
    private SettingProperties settingProperties;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public ServiceResult<String> checkCaptcha(String luotestResponse) {
        MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("api_key", settingProperties.getLuosimaoApiKey());
        paramMap.add("response", luotestResponse);
        ResponseEntity<String> response = null;
        try {
            response = restTemplate.postForEntity(settingProperties.getLuosimaoSiteUerifyUrl(), paramMap, String.class);
        } catch (Exception e) {
            log.error("请求Luosimao人机验证服务失败", e);
        }
        if (response != null && HttpStatus.OK.equals(response.getStatusCode())) {
            JSONObject jsonObject = JSON.parseObject(response.getBody());
            Integer error = jsonObject.getInteger("error");
            if (NumberUtils.INTEGER_ZERO.equals(error)) {
                return ServiceResult.success(response.getBody());
            } else {
                String msg = jsonObject.getString("msg");
                return ServiceResult.fail(ValidationErrorCodeEnum.CAPTCHA_ERROR, String.format("%s, %s, 验证错误, 请重试", error.toString(), msg));
            }
        }

        return ServiceResult.fail(ValidationErrorCodeEnum.CAPTCHA_ERROR, "验证错误, 请重试");
    }
}
